﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DNA.Mvc.jQuery;
using System.IO;
using System.Web.UI;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Web.WebPages;

namespace DNA.Mvc.UI
{
    public static class D2Extenstions
    {
        public static ComboBoxBuilder MasterCombo(this DnaControlFactory factory, string name, string selectedValue)
        {
            string[] masters = Directory.GetFiles(factory.ViewContext.HttpContext.Server.MapPath("~/Views/Shared"), "*.master");
            List<SelectableNode> masterNodes = new List<SelectableNode>();
            foreach (string master in masters)
            {
                DirectoryInfo dir = new DirectoryInfo(master);
                string masterName = Path.GetFileNameWithoutExtension(dir.FullName);
                masterNodes.Add(new SelectableNode()
                {
                    Value = masterName,
                    Title = masterName
                });
            }
            return factory.ComboBox(name)
                .DropDownStyle(DropdownStyles.DropdownList)
                .Bind(masterNodes, m => m.Title, m => m.Value)
                .Select(selectedValue) as ComboBoxBuilder;
        }

        //public static ListBoxBuilder ThemeListBox(this DnaControlFactory factory, string name,bool? allowSwitch=true)
        //{
        //    var Url = new UrlHelper(factory.ViewContext.RequestContext);
        //    Func<object, object> clientItemTmpl = new Func<object, object>(obj =>
        //    {
        //        var result = new HelperResult(writer =>
        //        {
        //            writer.Write("<li style=\"width: 80px; height: 90px; float: left; margin: 2px; border: 1px solid #cccccc;overflow: hidden;\" class=\"ui-corner-all\">");
        //            writer.Write("<input type=\"hidden\" value=\"${Title}\" />");
        //            writer.Write("<div style=\"padding-top: 5px;\" class=\"ui-corner-all\" title=\"${Title}\"><center>");
        //            writer.Write("<img src=\"${ImageUrl}?thumb=true&w=64&h=64\" alt=\"${Title}\" /></center></div>");
        //            writer.Write("<div style=\"text-align: center; white-space: pre-line;\" class=\"d-list-item-text\">");
        //            writer.Write("<span style=\"font-weight: normal;\">${Title}</span></div></li>");
        //        });
        //        return result;
        //    });

        //    var model = WebSite.Themes.ToList();
        //    foreach (var item in model)
        //    {
        //        item.ImageUrl = Url.Content(item.ImageUrl);
        //    }

        //    var _builder= factory.ListBox(name)
        //        .Options(opts => { opts.IsInlineMode = true; })
        //        .Bind(model)
        //        .ClientItemTemplate(clientItemTmpl);

        //    if (allowSwitch.Value)
        //        _builder.Options(opts => {
        //            opts.OnItemSelected= "$.post(\"" + Url.Action("LoadTheme", "Sys", new { Area = "" }) + "\",{ theme:ui.value},function(data){$(\"head link[href*='Content/Themes']\").remove();$(\"head\").append(data);});";
        //        });

        //    return _builder;
        //}

        public static ListBoxBuilder ImageFileListBox(this DnaControlFactory factory, string name, string url)
        {
            return ImageFileListBox(factory, name, url, "FLIST");
        }

        public static ListBoxBuilder ImageFileListBox(this DnaControlFactory factory, string name, string url, string httpMethod)
        {
            Func<object, object> clientItemTmpl = new Func<object, object>(obj =>
            {
                var result = new HelperResult(writer =>
                {
                    writer.Write("<li class=\"ui-corner-all\" style=\"width: 80px; height: 90px; float: left; margin: 2px; border: 1px solid #cccccc;overflow:hidden;\" title=\"${Name}\">");
                    writer.Write("<div style=\"padding-top: 5px;\"><center><img src=\"${Url}?thumb=true&w=64&h=64\" alt=\"${Name}\" /></center></div>");
                    writer.Write("<div style=\"text-align: center; width: 70px; white-space: pre-line;\" class=\"d-list-item-text\"><span style=\"font-weight:normal;\">${Name}</span></div><input type=\"hidden\" value=\"${Url}\" /></li>");
                });
                return result;
            });
            return factory.ListBox(name).Bind(url, httpMethod).ClientItemTemplate(clientItemTmpl);
        }

        public static string Help(this UrlHelper helper, int id)
        {
            var docs = (HelpDocs)DNA.Utility.XmlSerializerUtility.DeserializeFormXmlFile(HttpContext.Current.Server.MapPath(helper.Content("~/content/help.xml")), typeof(HelpDocs));
            var help = docs.Docs.FirstOrDefault(doc => doc.HelpID == id);
            if (!string.IsNullOrEmpty(help.HelpUrl))
                return help.HelpUrl;
            return "";
        }

        public static ButtonBuilder LocText(this ButtonBuilder builder, string resClass, string resKey)
        {
            var helper = new HtmlHelper(builder.ViewContext, builder.ViewDataContainer);
            if (string.IsNullOrEmpty(resClass))
                return builder.Text(helper.Global(resKey));
            else
                return builder.Text(helper.Global(resClass, resKey));
        }

        public static ButtonBuilder LocText(this ButtonBuilder builder, string reskey)
        {
            return builder.LocText(null, reskey);
        }

        public static UploaderBuilder Uploader(this DnaControlFactory factory, string target)
        {
            return new UploaderBuilder(new Uploader() { Name = target }, factory.ViewContext, factory.ViewDataContainer);
        }

        public static RichTextBoxBuilder WikiEditor(this DnaControlFactory factory, string name)
        {
            var rte = factory.RichTextBox(name)
                .AllowHTMLEditing(false)
                .Options(opts => { opts.Mode = "source"; })
                .Resizable()
                .ToolPanes(panes =>
                {
                    panes.Clear();

                    panes.Add().CustomTools(tb =>
                    {
                        tb.Add().AddCombo(combo =>
                        {
                            combo.Items(items =>
                            {
                                items.AddValue("blockquote", "((({0})))");
                                items.AddValue("Header 1", "=={0}==\r\n");
                                items.AddValue("Header 2", "==={0}===\r\n");
                                items.AddValue("Header 3", "===={0}====\r\n");
                                items.AddValue("Header 4", "====={0}====\r\n");
                                items.AddValue("Header 5", "======{0}======\r\n");
                            })
                            .Options(opts =>
                            {
                                opts.OnItemSelected = "$dna.insertFormat($(\"#" + name + "\"),ui.value);";
                            }).DropDownList();
                        });
                        //tb.Add().AddImage(Url.Content("~/content/images/wiki/bold.png"), "_insertMarkup($(\"#" + name + "\"),\"'''{0}'''\")", "Bold");
                    });
                });
            return rte;
        }

        public static WidgetViewBuilder Widget(this DnaControlFactory dna)
        {
            return new WidgetViewBuilder(new WidgetView() { }, dna.ViewContext, dna.ViewDataContainer);
        }

        public static WidgetZoneBuilder WidgetZone(this DnaControlFactory dna)
        {
            return WidgetZone(dna, "", "");
        }

        public static WidgetZoneBuilder WidgetZone(this DnaControlFactory dna, string title)
        {
            return WidgetZone(dna, title, "");
        }

        public static WidgetZoneBuilder WidgetZone(this DnaControlFactory dna, string title, string name)
        {
            return new WidgetZoneBuilder(new WidgetZone() { Name = name, Title = title }, dna.ViewContext, dna.ViewDataContainer).GenerateId();
        }
    }
}